package com.linjiang.protocol;

import com.linjiang.common.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http客户端
 */
public class HttpClient {

    /**
     * 发送请求
     * @return
     */
    public String send(String hostName, Integer port, Invocation invocation){
        try {
            URL url = new URL("http", hostName, port,"/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            //配置
            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            //发送请求
            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            //接收请求结果
            InputStream inputStream = httpURLConnection.getInputStream();
            String result = IOUtils.toString(inputStream);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
